// 事件系统服务

import type { GameEvent, EventChoice, Effect } from '@/types'
import { useGameStore, useResourcesStore, useBuildingsStore, useTechnologyStore, useShipsStore, useDiplomacyStore } from '@/stores'

export interface EventTemplate {
  id: string
  type: GameEvent['type']
  title: string
  description: string
  weight: number // 事件权重，影响触发概率
  conditions?: EventCondition[]
  effects?: Effect[]
  choices?: EventChoiceTemplate[]
  cooldown?: number // 冷却时间（毫秒）
  maxOccurrences?: number // 最大触发次数
}

export interface EventCondition {
  type: 'resource' | 'building' | 'technology' | 'ship' | 'diplomacy' | 'time' | 'achievement'
  target: string
  operator: 'gt' | 'gte' | 'lt' | 'lte' | 'eq' | 'neq' | 'exists' | 'not_exists'
  value: any
}

export interface EventChoiceTemplate {
  id: string
  text: string
  conditions?: EventCondition[]
  effects?: Effect[]
  probability?: number // 选择成功概率
}

export class EventSystem {
  private static instance: EventSystem
  private eventTemplates: Map<string, EventTemplate> = new Map()
  private eventHistory: Map<string, number[]> = new Map() // 事件ID -> 触发时间列表
  private eventCooldowns: Map<string, number> = new Map() // 事件ID -> 下次可触发时间

  // Store引用
  private gameStore = useGameStore()
  private resourcesStore = useResourcesStore()
  private buildingsStore = useBuildingsStore()
  private technologyStore = useTechnologyStore()
  private shipsStore = useShipsStore()
  private diplomacyStore = useDiplomacyStore()

  static getInstance(): EventSystem {
    if (!EventSystem.instance) {
      EventSystem.instance = new EventSystem()
    }
    return EventSystem.instance
  }

  // 初始化事件系统
  static async initialize(): Promise<void> {
    try {
      console.log('📡 初始化事件系统...')
      
      // 获取实例以确保单例模式正常工作
      const instance = EventSystem.getInstance()
      
      // 事件系统已经在构造函数中初始化了事件模板
      // 这里可以添加额外的初始化逻辑
      
      console.log('✅ 事件系统初始化完成')
    } catch (error) {
      console.error('❌ 事件系统初始化失败:', error)
      throw new Error(`事件系统初始化失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  constructor() {
    this.initializeEventTemplates()
  }

  // 初始化事件模板
  private initializeEventTemplates(): void {
    // 资源相关事件
    this.registerEvent({
      id: 'asteroid_mining_discovery',
      type: 'opportunity',
      title: '小行星带发现',
      description: '我们的探测器在附近发现了一个富含矿物的小行星带。',
      weight: 10,
      conditions: [
        { type: 'technology', target: 'asteroid_mining', operator: 'exists', value: true }
      ],
      choices: [
        {
          id: 'mine_immediately',
          text: '立即开采',
          effects: [
            { type: 'resource', target: 'metals', modifier: 2000, description: '获得2000金属' },
            { type: 'resource', target: 'rare_metals', modifier: 500, description: '获得500稀有金属' }
          ]
        },
        {
          id: 'establish_mining_station',
          text: '建立采矿站',
          conditions: [
            { type: 'resource', target: 'credits', operator: 'gte', value: 5000 }
          ],
          effects: [
            { type: 'resource', target: 'credits', modifier: -5000, description: '花费5000信用点' },
            { type: 'building', target: 'mining_station', modifier: 1, description: '获得1个采矿站' }
          ]
        },
        {
          id: 'ignore',
          text: '忽略',
          effects: []
        }
      ],
      cooldown: 1800000, // 30分钟
      maxOccurrences: 5
    })

    this.registerEvent({
      id: 'energy_crisis',
      type: 'crisis',
      title: '能源危机',
      description: '由于设备老化，我们的能源产量急剧下降。',
      weight: 8,
      conditions: [
        { type: 'resource', target: 'energy', operator: 'lt', value: 1000 }
      ],
      effects: [
        { type: 'resource', target: 'energy', modifier: -500, description: '失去500能量' }
      ],
      choices: [
        {
          id: 'emergency_repairs',
          text: '紧急维修',
          effects: [
            { type: 'resource', target: 'metals', modifier: -1000, description: '消耗1000金属' },
            { type: 'resource', target: 'energy', modifier: 1500, description: '恢复1500能量' }
          ]
        },
        {
          id: 'rationing',
          text: '实施配给制',
          effects: [
            { type: 'resource', target: 'energy', modifier: 200, description: '节约200能量' }
          ]
        }
      ],
      cooldown: 3600000 // 1小时
    })

    // 外交相关事件
    this.registerEvent({
      id: 'trade_delegation',
      type: 'opportunity',
      title: '贸易代表团',
      description: '一个友好派系的贸易代表团希望与我们建立贸易关系。',
      weight: 12,
      conditions: [
        { type: 'diplomacy', target: 'friendly_factions', operator: 'gt', value: 0 }
      ],
      choices: [
        {
          id: 'accept_trade',
          text: '接受贸易协议',
          effects: [
            { type: 'resource', target: 'credits', modifier: 3000, description: '获得3000信用点' }
          ]
        },
        {
          id: 'negotiate_better_terms',
          text: '谈判更好条件',
          probability: 0.6,
          effects: [
            { type: 'resource', target: 'credits', modifier: 5000, description: '获得5000信用点' }
          ]
        },
        {
          id: 'decline',
          text: '拒绝',
          effects: []
        }
      ],
      cooldown: 2700000 // 45分钟
    })

    // 科技相关事件
    this.registerEvent({
      id: 'research_breakthrough',
      type: 'opportunity',
      title: '研究突破',
      description: '我们的科学家在实验中取得了意外的突破。',
      weight: 6,
      conditions: [
        { type: 'building', target: 'research_lab', operator: 'gte', value: 1 }
      ],
      choices: [
        {
          id: 'focus_research',
          text: '集中研究资源',
          effects: [
            { type: 'resource', target: 'research_points', modifier: 1000, description: '获得1000研究点数' }
          ]
        },
        {
          id: 'publish_findings',
          text: '发布研究成果',
          effects: [
            { type: 'resource', target: 'influence', modifier: 500, description: '获得500影响力' }
          ]
        }
      ],
      cooldown: 5400000 // 1.5小时
    })

    // 军事相关事件
    this.registerEvent({
      id: 'pirate_raid',
      type: 'crisis',
      title: '海盗袭击',
      description: '海盗舰队正在接近我们的边境，威胁我们的贸易路线。',
      weight: 15,
      conditions: [
        { type: 'ship', target: 'total_ships', operator: 'gt', value: 0 }
      ],
      choices: [
        {
          id: 'military_response',
          text: '军事回应',
          conditions: [
            { type: 'ship', target: 'military_ships', operator: 'gte', value: 3 }
          ],
          probability: 0.8,
          effects: [
            { type: 'resource', target: 'credits', modifier: 2000, description: '缴获2000信用点' }
          ]
        },
        {
          id: 'pay_tribute',
          text: '支付保护费',
          effects: [
            { type: 'resource', target: 'credits', modifier: -1500, description: '支付1500信用点' }
          ]
        },
        {
          id: 'evacuate_trade_routes',
          text: '撤离贸易路线',
          effects: [
            { type: 'resource', target: 'credits', modifier: -500, description: '损失500信用点收入' }
          ]
        }
      ],
      cooldown: 1800000 // 30分钟
    })

    // 探索相关事件
    this.registerEvent({
      id: 'ancient_artifact',
      type: 'mystery',
      title: '古代遗物',
      description: '探索队在一个废弃的空间站中发现了神秘的古代遗物。',
      weight: 4,
      conditions: [
        { type: 'ship', target: 'exploration_ships', operator: 'gte', value: 1 }
      ],
      choices: [
        {
          id: 'study_artifact',
          text: '研究遗物',
          effects: [
            { type: 'technology', target: 'random_tech', modifier: 1, description: '解锁随机科技' }
          ]
        },
        {
          id: 'sell_artifact',
          text: '出售遗物',
          effects: [
            { type: 'resource', target: 'credits', modifier: 10000, description: '获得10000信用点' }
          ]
        },
        {
          id: 'display_artifact',
          text: '展示遗物',
          effects: [
            { type: 'resource', target: 'influence', modifier: 1000, description: '获得1000影响力' }
          ]
        }
      ],
      cooldown: 7200000, // 2小时
      maxOccurrences: 3
    })
  }

  // 注册事件模板
  registerEvent(template: EventTemplate): void {
    this.eventTemplates.set(template.id, template)
  }

  // 生成随机事件
  generateRandomEvent(): GameEvent | null {
    const availableEvents = this.getAvailableEvents()
    if (availableEvents.length === 0) return null

    // 基于权重选择事件
    const totalWeight = availableEvents.reduce((sum, event) => sum + event.weight, 0)
    let randomValue = Math.random() * totalWeight
    
    for (const template of availableEvents) {
      randomValue -= template.weight
      if (randomValue <= 0) {
        return this.createEventFromTemplate(template)
      }
    }

    return null
  }

  // 获取可用事件列表
  private getAvailableEvents(): EventTemplate[] {
    const currentTime = Date.now()
    
    return Array.from(this.eventTemplates.values()).filter(template => {
      // 检查冷却时间
      const nextAvailableTime = this.eventCooldowns.get(template.id) || 0
      if (currentTime < nextAvailableTime) return false

      // 检查最大触发次数
      if (template.maxOccurrences) {
        const occurrences = this.eventHistory.get(template.id)?.length || 0
        if (occurrences >= template.maxOccurrences) return false
      }

      // 检查触发条件
      return this.checkEventConditions(template.conditions || [])
    })
  }

  // 检查事件条件
  private checkEventConditions(conditions: EventCondition[]): boolean {
    return conditions.every(condition => this.checkCondition(condition))
  }

  // 检查单个条件
  private checkCondition(condition: EventCondition): boolean {
    let actualValue: any

    switch (condition.type) {
      case 'resource':
        actualValue = this.resourcesStore.getResource(condition.target)
        break
      case 'building':
        if (condition.target === 'total_buildings') {
          actualValue = this.buildingsStore.buildings.length
        } else {
          actualValue = this.buildingsStore.getBuildingCount(condition.target)
        }
        break
      case 'technology':
        actualValue = this.technologyStore.isTechnologyResearched(condition.target)
        break
      case 'ship':
        if (condition.target === 'total_ships') {
          actualValue = this.shipsStore.ships.length
        } else if (condition.target === 'military_ships') {
          actualValue = this.shipsStore.militaryShips.length
        } else if (condition.target === 'exploration_ships') {
          actualValue = this.shipsStore.ships.filter(ship => ship.type === 'exploration').length
        }
        break
      case 'diplomacy':
        if (condition.target === 'friendly_factions') {
          actualValue = this.diplomacyStore.neutralFactions.length + this.diplomacyStore.alliedFactions.length
        }
        break
      case 'time':
        actualValue = this.gameStore.gameTime
        break
      case 'achievement':
        actualValue = this.gameStore.isAchievementUnlocked(condition.target)
        break
      default:
        return false
    }

    return this.compareValues(actualValue, condition.operator, condition.value)
  }

  // 比较值
  private compareValues(actual: any, operator: string, expected: any): boolean {
    switch (operator) {
      case 'gt': return actual > expected
      case 'gte': return actual >= expected
      case 'lt': return actual < expected
      case 'lte': return actual <= expected
      case 'eq': return actual === expected
      case 'neq': return actual !== expected
      case 'exists': return actual !== undefined && actual !== null
      case 'not_exists': return actual === undefined || actual === null
      default: return false
    }
  }

  // 从模板创建事件
  private createEventFromTemplate(template: EventTemplate): GameEvent {
    const eventId = `${template.id}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    // 记录事件历史
    const history = this.eventHistory.get(template.id) || []
    history.push(Date.now())
    this.eventHistory.set(template.id, history)

    // 设置冷却时间
    if (template.cooldown) {
      this.eventCooldowns.set(template.id, Date.now() + template.cooldown)
    }

    // 转换选择模板为实际选择
    const choices: EventChoice[] = (template.choices || []).map(choiceTemplate => ({
      id: choiceTemplate.id,
      text: choiceTemplate.text,
      effects: choiceTemplate.effects || []
    }))

    return {
      id: eventId,
      type: template.type,
      title: template.title,
      description: template.description,
      effects: template.effects || [],
      choices,
      isActive: true,
      createdAt: Date.now()
    }
  }

  // 处理事件选择
  processEventChoice(eventId: string, choiceId: string): boolean {
    const event = this.gameStore.getEvent(eventId)
    if (!event) return false

    const choice = event.choices.find(c => c.id === choiceId)
    if (!choice) return false

    // 获取原始模板以检查概率
    const templateId = eventId.split('_')[0]
    const template = this.eventTemplates.get(templateId)
    const choiceTemplate = template?.choices?.find(c => c.id === choiceId)

    // 检查选择条件
    if (choiceTemplate?.conditions && !this.checkEventConditions(choiceTemplate.conditions)) {
      return false
    }

    // 检查成功概率
    if (choiceTemplate?.probability && Math.random() > choiceTemplate.probability) {
      // 选择失败，可能有负面后果
      this.gameStore.addEvent({
        id: `${eventId}_failure`,
        type: 'consequence',
        title: '行动失败',
        description: '你的行动没有达到预期效果。',
        effects: [],
        choices: [],
        isActive: true,
        createdAt: Date.now()
      })
      return false
    }

    // 应用选择效果
    choice.effects.forEach(effect => {
      this.applyEffect(effect)
    })

    // 标记事件为已处理
    this.gameStore.markEventAsProcessed(eventId)
    return true
  }

  // 应用效果
  private applyEffect(effect: Effect): void {
    switch (effect.type) {
      case 'resource':
        if (effect.modifier > 0) {
          this.resourcesStore.addResource(effect.target, effect.modifier)
        } else {
          this.resourcesStore.removeResource(effect.target, Math.abs(effect.modifier))
        }
        break
      case 'building':
        // 应用建筑效果
        break
      case 'technology':
        if (effect.target === 'random_tech') {
          // 解锁随机科技
          const availableTechs = this.technologyStore.availableTechnologies
          if (availableTechs.length > 0) {
            const randomTech = availableTechs[Math.floor(Math.random() * availableTechs.length)]
            this.technologyStore.unlockTechnology(randomTech.id)
          }
        } else {
          this.technologyStore.unlockTechnology(effect.target)
        }
        break
      case 'ship':
        // 应用舰船效果
        break
      case 'diplomacy':
        // 应用外交效果
        break
    }
  }

  // 获取事件历史
  getEventHistory(eventId: string): number[] {
    return this.eventHistory.get(eventId) || []
  }

  // 获取事件统计
  getEventStatistics() {
    const stats = {
      totalEvents: 0,
      eventsByType: {} as Record<string, number>,
      mostFrequentEvent: '',
      maxFrequency: 0
    }

    this.eventHistory.forEach((occurrences, eventId) => {
      stats.totalEvents += occurrences.length
      
      const template = this.eventTemplates.get(eventId)
      if (template) {
        const type = template.type
        stats.eventsByType[type] = (stats.eventsByType[type] || 0) + occurrences.length
        
        if (occurrences.length > stats.maxFrequency) {
          stats.maxFrequency = occurrences.length
          stats.mostFrequentEvent = eventId
        }
      }
    })

    return stats
  }

  // 重置事件系统
  reset(): void {
    this.eventHistory.clear()
    this.eventCooldowns.clear()
  }
}